import React, { useState, useEffect } from 'react';

function FunctionState() {
    // console.log("函数被执行");

    const initialTimer = 1;

    const [timer, setTimer] = useState(initialTimer);
  const [hello, setHello] = useState('hi');

    useEffect(() => {
        // console.log('Effect 被执行');
      //   setInterval(() => {
      //       // console.log('Timer + 1');
      //       // js的闭包 ※
      //       setTimer((oldTimer) => oldTimer + 1);
      // }, 1000);

      setTimeout(() => {
        setTimer(timer + 1);
        setHello(hello + 'hi~');
      }, 1000);
      // 销毁定时器
      return () => {
        // console.log('清理'); // 2遍
        clearTimeout(timer);
      };
    }, [timer, hello]);

  // useEffect(() => {
  //   setHello(hello + '我好了');
  // }, [hello]);
  
    const onMultiplyClick = () => {
        setTimer(timer * 2);
    };

    const onMinusClick = () => {
        setTimer(timer - 1);
    };

    const onResetClick = () => {
        setTimer(initialTimer);
    };

    return (
      <>
        <button onClick={onMultiplyClick}>当前数×2</button>
        <button onClick={onMinusClick}>当前数-1</button>
        <button onClick={onResetClick}>重置</button>
        <h3>{hello}</h3>
        <div>第一个函数组件：{timer}</div>
      </>
    );
}

export default FunctionState;